package com.finger.gulimall.member.config;

import javax.servlet.http.HttpServletRequest;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @ClassName FeignConfig
 * @Description TODO
 * @Author finger
 * @Date 2022/7/5 22:47
 * @Version 1.0
 */

@Configuration
public class FeignConfig {

    /**
     * 给容器中添加RequestInterceptor组件，
     * 增强Feign远程调用请求，给每次远程调用请求头中设置Cookie信息
     * @return RequestInterceptor
     */
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate requestTemplate) {

                RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

                if(requestAttributes!=null){
                    // 如果feign远程调用时，请求域不为空，就说明我们手动设置需要请求头中的JESSIONID信息
                    ServletRequestAttributes attributes = (ServletRequestAttributes)requestAttributes;
                    HttpServletRequest request = attributes.getRequest();
                    String cookie = request.getHeader("Cookie");
                    // 如果在登录的情况下，老请求头包含登录Cookie信息，新请求不带登录Cookie去远程调用购物车服务，会被购物车服务认为未登录。
                    // 所以设置一个Feign远程请求拦截，在发送远程请求之前将老请求头中的Cookie信息设置到新请求中，新请求去请求远程服务
                    requestTemplate.header("Cookie",cookie);
                }
            }
        };
    }
}
